<template>
  <transition name="el-zoom-in-center">
    <div class="jsbos-preview-main">
      <div class="jsbos-common-page-header">
        <el-page-header
          @back="goBack"
          :content="!dataForm.id ? '新建' : '编辑'"
        />
        <div class="options">
          <el-button type="primary" @click="dataFormSubmit()"> 保 存</el-button>
          <el-button @click="goBack"> 取 消</el-button>
        </div>
      </div>
      <el-row
        :gutter="15"
        class="main"
        :style="{ margin: '0 auto', width: '100%' }"
      >
        <el-form
          ref="elForm"
          :model="dataForm"
          :rules="rules"
          size="small"
          label-width="80px"
          label-position="right"
        >
          <template v-if="!loading">
            <el-col :span="24">
              <el-form-item label="通知范围" prop="toType">
                <el-radio-group v-model="dataForm.toType">
                  <el-radio label="1">指定成员</el-radio>
                  <el-radio label="2">部门成员</el-radio>
                  <el-radio label="3">全部成员</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dataForm.toType == '1'">
              <el-form-item label="接收人" prop="toUserIds">
                <user-select
                  v-model="dataForm.toUserIds"
                  placeholder="请选择"
                  clearable
                  :multiple="true"
                >
                </user-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="dataForm.toType == '2'">
              <el-form-item label="接收部门" prop="toDeptIds">
                <dep-select
                  v-model="dataForm.toDeptIds"
                  placeholder="请选择"
                  clearable
                  :multiple="true"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="业务系统" prop="taskCode">
                <el-input
                  v-model="dataForm.taskCode"
                  placeholder="请输入"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="24" :lg="12" :xl="12">
              <el-form-item label="发送配置" prop="sendCode">
                <MsgSendDialog
                  v-model="dataForm.sendCode"
                  :title="dataForm.sendName"
                  @change="onMsgSendChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="描述" prop="remark">
                <el-input
                  v-model="dataForm.remark"
                  placeholder="请输入"
                  :style="{ width: '100%' }"
                  true
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 4 }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="0">
                <div class="jsbos-common-title">
                  <h2>{{ keyWordTitle }}</h2>
                </div>
                <el-table :data="keywordList" size="mini">
                  <el-table-column
                    type="index"
                    width="50"
                    label="序号"
                    :align="'center'"
                  />
                  <el-table-column prop="lable" label="变量" width="300">
                    <template slot="header"> 变量 </template>
                    <template slot-scope="scope">
                      <el-input
                        readonly
                        v-model="scope.row.lable"
                        placeholder="请输入"
                        clearable
                        :style="{ width: '100%' }"
                      >
                      </el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="value" label="内容">
                    <template slot="header"> 内容 </template>
                    <template slot-scope="scope">
                      <!-- 变量：{{ scope.row.lable }} -->
                      <el-input
                        v-model="scope.row.value"
                        placeholder="请输入"
                        clearable
                        :style="{ width: '100%' }"
                        true
                        type="textarea"
                        :rows="1"
                        :autosize="{ minRows: 1, maxRows: 4 }"
                      >
                      </el-input>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="0">
                <div class="jsbos-common-title">
                  <h2>定制参数</h2>
                </div>
                <el-table :data="customKeyList" size="mini">
                  <el-table-column
                    type="index"
                    width="50"
                    label="序号"
                    :align="'center'"
                  />
                  <el-table-column prop="keyName" label="参数名" width="300">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.keyName"
                        placeholder="请输入"
                        clearable
                        :style="{ width: '100%' }"
                      >
                      </el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="keyValue" label="注释">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.keyValue"
                        placeholder="请输入"
                        clearable
                        :style="{ width: '100%' }"
                        true
                        type="textarea"
                        :rows="1"
                        :autosize="{ minRows: 1, maxRows: 4 }"
                      >
                      </el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="50">
                    <template slot-scope="scope">
                      <el-button
                        v-show="scope.row.closable"
                        size="mini"
                        type="text"
                        class="jsbos-table-delBtn"
                        @click="delCustomKeyList(scope.$index)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
                <div class="table-actions" @click="addCustomKeyList()">
                  <el-button type="text" icon="el-icon-plus">添加</el-button>
                </div>
              </el-form-item>
            </el-col>
          </template>
        </el-form>
      </el-row>
    </div>
  </transition>
</template>
<script>
import { getInfo, Update, Create } from "@/views/message/api/mcTaskMsg";
import MsgSendDialog from "./msgSendDialog";
export default {
  components: { MsgSendDialog },
  props: [],
  data() {
    return {
      visible: false,
      loading: false,
      dataForm: {
        taskCode: "",
        sendCode: "",
        sendName: "",
        businessKey: "",
        customKey: "",
        toType: "1",
        toUserIds: [],
        toDeptIds: [],
        description: "",
        enabledMark: "1",
      },
      rules: {
        taskCode: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        sendCode: [
          {
            required: true,
            message: "请选择",
            trigger: "blur",
          },
        ],
        enabledMark: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        toUserIds: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
        toDeptIds: [
          {
            required: true,
            message: "请至少选择一个",
            trigger: "change",
          },
        ],
      },
      enabledMarkOptions: [
        { fullName: "待发送", id: "1" },
        { fullName: "已发送", id: "2" },
      ],
      keyWordTitle: "关键参数",
      keywordList: [],
      customKeyList: [],
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    goBack() {
      this.$emit("refresh");
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          getInfo(this.dataForm.id).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.taskCode = "消息中心";
          this.dataForm.toType = "1";
          this.dataForm.enabledMark = "1";
          this.dataForm.sendCode = "";
          this.dataForm.sendName = "";
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          var _data = this.dataList();
          this.btnLoading = true;
          const formMethod = this.dataForm.id ? Update : Create;
          formMethod(_data)
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refresh", true);
                },
              });
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    addCustomKeyList() {
      let item = {
        keyName: undefined,
        keyValue: undefined,
      };
      this.customKeyList.push(item);
    },
    delCustomKeyList(index) {
      this.customKeyList.splice(index, 1);
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      // _data.toUserIds = _data.toUserIds.join(",");
      // _data.toDeptIds = _data.toDeptIds.join(",");
      if (_data.toType == "1") {
        _data.toUserIds = _data.toUserIds.join(",");
        _data.toDeptIds = "";
      }
      if (_data.toType == "2") {
        _data.toUserIds = "";
        _data.toDeptIds = _data.toDeptIds.join(",");
      }
      if (_data.toType == "3") {
        _data.toUserIds = "@ALL";
        _data.toDeptIds = "";
      }
      if (this.keywordList) {
        const obj = {};
        this.keywordList.map((item) => {
          const elementId = item["lable"];
          obj[elementId] = item.value;
        });
        _data.businessKey = JSON.stringify(obj);
      }
      if (this.customKeyList) {
        const obj = {};
        this.customKeyList.map((item) => {
          console.log(item, "item");
          console.log(item["keyName"], `item["keyName"]`);
          console.log(item.keyValue, "item.keyValue");
          const elementId = item["keyName"];
          obj[elementId] = item.keyValue;
        });
        _data.customKey = JSON.stringify(obj);
      }
      console.log(_data);
      return _data;
    },
    dataInfo(dataAll) {
      console.log("dataAll", dataAll);
      let _dataAll = dataAll;
      _dataAll.toUserIds = _dataAll.toUserIds
        ? _dataAll.toUserIds.split(",")
        : [];
      _dataAll.toDeptIds = _dataAll.toDeptIds
        ? _dataAll.toDeptIds.split(",")
        : [];
      if (_dataAll.businessKey) {
        const obj = JSON.parse(_dataAll.businessKey);
        const keys = Object.keys(obj);
        this.keywordList = keys.map((key) => {
          return { lable: key, value: obj[key] };
        });
        console.log(this.keywordList);
      }
      if (_dataAll.customKey) {
        const obj = JSON.parse(_dataAll.customKey);
        const keys = Object.keys(obj);
        this.customKeyList = keys.map((key) => {
          return { keyName: key, keyValue: obj[key] };
        });
        console.log(this.customKeyList);
      }
      this.dataForm = _dataAll;
    },
    /**消息模板change事件 */
    onMsgSendChange(enCode, item) {
      if (!enCode) return (this.dataForm.sendName = "");
      this.dataForm.sendCode = enCode;
      this.dataForm.sendName = item.fullName;
      if (item.businessInfoVO && item.businessInfoVO.keywordList) {
        this.keywordList = item.businessInfoVO.keywordList.map((item) => {
          return { lable: item.enCode, value: "" };
        });
      }
    },
  },
};
</script>
